package com.example.vertification.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.vertification.entity.User;
import com.example.vertification.entity.UserShop;
import com.example.vertification.entity.UserStation;
import com.example.vertification.service.OrderService;
import com.example.vertification.service.UserService;
import com.example.vertification.service.UserShopService;
import com.example.vertification.service.UserStationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.example.vertification.entity.Order;
@RestController
@Api(value = "企业店铺管理", tags = "企业店铺管理")
public class UserShopController {

    private final UserService userService;
    private final UserShopService userShopService;
    private final UserStationService userStationService;

    private final OrderService orderService;


    @Autowired
    public UserShopController(UserService userService, UserShopService userShopService,UserStationService userStationService,OrderService orderService) {
        this.userService = userService;
        this.userShopService = userShopService;
        this.userStationService = userStationService;
        this.orderService = orderService;
    }



    @PostMapping("/set_shop_desc")
    @ApiOperation(value = "传入类型为对象,该企业账号的token,企业介绍description")
    public ResponseEntity<?> set_shop_desc(@RequestBody String body) throws IOException {
        JSONObject obj_get = JSONUtil.parseObj(body);

        User u = userService.getUserByToken(obj_get.getStr("token"));
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }

        UserShop us = userShopService.getEntityByUid(u.getUid());
        if(us==null){
            us = new UserShop(u.getUid(),"","", UserShop.TradeType.ALL,0,new Date().getTime());
        }
        us.setDescription(obj_get.getStr("description"));
        userShopService.save(us);
        return ResponseEntity.ok("success");
    }

    @PostMapping("/set_shop_trade")
    @ApiOperation(value = "传入类型为对象,该企业账号的token,企业交易类型trade字符串（ALL/OnlySelf/OnlyYourself）")
    public ResponseEntity<?> set_shop_trade(@RequestBody String body) throws IOException {
        JSONObject obj_get = JSONUtil.parseObj(body);

        User u = userService.getUserByToken(obj_get.getStr("token"));
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }

        UserShop us = userShopService.getEntityByUid(u.getUid());
        if(us==null){
            us = new UserShop(u.getUid(),"","", UserShop.TradeType.ALL,0,new Date().getTime());
        }
        us.setType(UserShop.TradeType.valueOf(obj_get.getStr("trade")));
        userShopService.save(us);
        return ResponseEntity.ok("success");
    }


    @PostMapping("/set_shop_buys")
    @ApiOperation(value = "传入类型为对象,该企业账号的token,企业店铺需求购买的数组buys:[{type:'AAA',amount: 188,price:10},]")
    public ResponseEntity<?> set_shop_buys(@RequestBody String body) throws IOException {
        System.out.println(body);
        JSONObject obj_get = JSONUtil.parseObj(body);
        User u = userService.getUserByToken(obj_get.getStr("token"));
        if(u==null){
            return ResponseEntity.ok("请先登入!");
        }

        UserShop us = userShopService.getEntityByUid(u.getUid());
        if(us==null){
            us = new UserShop(u.getUid(),"","", UserShop.TradeType.ALL,0,new Date().getTime());
        }
        JSONArray ja = JSONUtil.parseArray(obj_get.getStr("buys"));
        us.setBuys(JSONUtil.toJsonStr(ja));
        userShopService.save(us);
        return ResponseEntity.ok("success");
    }


    @GetMapping("/get_shop")
    @ApiOperation(value = "传入店铺的店主uid")
    public ResponseEntity<?> get_stations(@RequestParam String uid) throws IOException {
        UserShop us = userShopService.getEntityByUid(Long.parseLong(uid));
        if(us==null){
            us = new UserShop(Long.valueOf(uid),"","[]", UserShop.TradeType.ALL,0,new Date().getTime());
            userShopService.save(us);
        }
        User u = userService.getUserByUId(us.getUid());
        UserStation usa = userStationService.getEntityByUid(us.getUid());
        u.setPassword("****");
        JSONObject obj = JSONUtil.parseObj(us);
        obj.set("user",JSONUtil.parse(u));
        if(obj.getStr("buys").trim().length() !=0){
            obj.set("buys",JSONUtil.parseArray(obj.getStr("buys")));
        }else{
            obj.set("buys",new JSONArray());
        }
        if(usa!=null&&usa.getStations()!=null&&!usa.getStations().trim().equalsIgnoreCase("")){
            obj.set("stations",JSONUtil.parseArray(usa.getStations()));
        }

        List<Order> order_list = orderService.getAllBuysByUserID(u.getUid());
        obj.set("has_done_orders",0);
        if(order_list != null){
            obj.set("has_done_orders",order_list.size());
        }

        ArrayList<String> collect_ways = new ArrayList<String>();
        if(order_list!=null){
            for(Order o : order_list){
                if(o.getCollect_way()==null){
                    continue;
                }
                JSONArray collect_list = JSONUtil.parseArray(o.getCollect_way());
                for(int d =0;d<collect_list.size();d++){
                    String temp_str = String.valueOf(collect_list.get(d));
                    if(!collect_ways.contains(temp_str)){
                        collect_ways.add(temp_str);
                    }
                }
            }
        }


        obj.set("collect_ways",collect_ways);
        return ResponseEntity.ok(obj);
    }

    @GetMapping("/get_shops")
    @ApiOperation(value = "获得所有店铺列表")
    public ResponseEntity<?> get_shops() throws IOException {
        List<UserShop> us = userShopService.findAll();
        JSONArray list = JSONUtil.parseArray(us);
        for(int i = 0;i<list.size();i++){
            JSONObject obj = (JSONObject) list.get(i);
            UserStation usa = userStationService.getEntityByUid(obj.getLong("uid"));
            if(usa==null){
                continue;
            }
            if(usa.getStations() == null || usa.getStations().trim().equalsIgnoreCase("")){
                continue;
            }
            obj.set("buys",JSONUtil.parseArray(obj.getStr("buys")));
            obj.set("stations",JSONUtil.parseArray(usa.getStations()));
            User u = userService.getUserByUId(obj.getLong("uid"));
            u.setPassword("****");
            obj.set("user",JSONUtil.parse(u));
            list.set(i,obj);
        }

        return ResponseEntity.ok(list);
    }


    @Value("${shop-img-path}")
    private  String shops_head;

    @PostMapping("/upload_shop_headimg")
    @ApiOperation(value = "上传店铺头像,传入登入口令token，头像文件")
    public ResponseEntity<?> upload_headimg(@RequestParam String token, MultipartFile file) throws IllegalStateException, IOException {
        User u = userService.getUserByToken(token);
        if(u == null) {
            return new ResponseEntity<>("未登入,请先登录在进行操作" , HttpStatus.OK);
        }
        long maxFileSizeInBytes = 5*1024 * 1024; // 1MB
        if (file.getSize() > maxFileSizeInBytes) {
            return new ResponseEntity<>("文件大小超过限制，请上传小于5MB的图片" ,HttpStatus.OK);
        }
        // 构建保存图片的目录路径
        String filePath = shops_head.replace("file:","");
        File filee=new File(filePath);
        if(!filee.exists()){
            filee.mkdirs();
        }
        //新文件的路径
        file.transferTo(new File(filePath + u.getUid() + ".jpg"));
        userService.saveUser(u);
        return  new ResponseEntity<>("成功",HttpStatus.OK);
    }


}
